using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public class LoadAbTest1 : MonoBehaviour
{
    public Image image;
    // Start is called before the first frame update
    //string assetNameCube = "cube";
    AssetBundle assBundleCube;
    AssetBundle abMain;
    AssetBundle abHead;
    void Start()
    {
        abMain = AssetBundle.LoadFromFile(Application.streamingAssetsPath + "/StandaloneWindows");
        //加载主包中的固定文件   
        AssetBundleManifest abMainManifest = abMain.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
        //从固定文件中获得依赖信息
        string[] strs = abMainManifest.GetAllDependencies("cube");
        for (int i = 0; i < strs.Length; i++)
        {
            Debug.Log(strs[i]);
        }
        //abHead= AssetBundle.load
        string cubePath = Application.streamingAssetsPath + "/cube";
        //ab包不能重复加载   否则报错
        assBundleCube = AssetBundle.LoadFromFile(cubePath);
        // var cube = ab.LoadAsset<GameObject>("Cube");
        var cube = assBundleCube.LoadAsset("Cube", typeof(GameObject)) as GameObject;
        Instantiate(cube);



        // StartCoroutine(LoadABRes("humanimage", "cunzhang"));

    }

    public T LoadSyncAssetBundle<T>() {


        return default;
    }
    /// <summary>
    /// 异步资源加载
    /// </summary>
    /// <param name="abName"></param>
    /// <param name="resName"></param>
    /// <returns></returns>
    IEnumerator LoadASyncAssetBundle<T>(string abName, string resName,Action<T> callBack)
    {

        AssetBundleCreateRequest abCr = AssetBundle.LoadFromFileAsync(Application.streamingAssetsPath + $"/{abName}");
        yield return abCr;
        AssetBundleRequest abq = abCr.assetBundle.LoadAssetAsync(resName, typeof(Sprite));
        yield return abq;
        //image.sprite = abq.asset as Sprite;
    }


    /// <summary>
    /// 异步资源加载
    /// </summary>
    /// <param name="abName"></param>
    /// <param name="resName"></param>
    /// <returns></returns>
    IEnumerator LoadABRes(string abName,string resName) {

        AssetBundleCreateRequest abCr = AssetBundle.LoadFromFileAsync(Application.streamingAssetsPath + $"/{abName}");
        yield return abCr;
        AssetBundleRequest abq = abCr.assetBundle.LoadAssetAsync(resName, typeof(Sprite));
        yield return abq;
        image.sprite = abq.asset as Sprite;
    }
    public void UnLoadAssetBundle() {
        //ab包卸载  
        //卸载所有ab包资源   如果位true  则会卸载ab包加载的资源 不包括实例化的资源 
        AssetBundle.UnloadAllAssetBundles(true);

        //卸载ab包
        assBundleCube.Unload(true);
    }
    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space)){
            UnLoadAssetBundle();
        }
    }
}
